const express = require("express");
const { ValidationError } = require("../utils/errors")
const router = express.Router();
const { loginService,updateAdminService } = require("../service/adminService")
const { formatResponse,analysisToken } = require("../utils/tool")

router.post('/login',async function(req,res,next){
    try {
        if(req.query.captcha.toLowerCase()!==req.session.captcha.toLowerCase()){
            throw new ValidationError("验证码有误")
        }
        const result = await loginService(req.query)
        if(result.token){
            res.setHeader("Authorization",result.token)
        }
        const {id,loginId,name} = result.data
        res.send(formatResponse(0,'',{
            id,
            loginId,
            name
        }));   
    } catch (error) {
        res.send(formatResponse(500,error.message)); 
    }
})

router.get('/login',async function(req,res,next){
    try {
        const token = req.get("Authorization")
        const data = analysisToken(token)
        const { loginId,name,id } = data
        res.send(formatResponse(200,"",{
            loginId,
            name,
            id
        }))
    } catch (error) {
        console.log(error,'/loginget');
    }
})

router.put('/',async function(req,res,next){
    const result = await updateAdminService(req.query)
    res.send(result)
})

module.exports = router;